import React from 'react';
import { useState,useEffect } from 'react';
import s from './style.module.less';
import { Cell } from 'zarm';
import dayjs from 'dayjs';
import { useNavigate } from 'react-router-dom'

function BillItem({ bill }) {
  const [expense,setExpense] = useState(0);
  const [income,setIncome] = useState(0);
  const navigate = useNavigate();
  // useEffect(() => {
  //   bill.map((item,index) => {
  //     item.map((bills,index) => {
  //       if(bills[index].pay_type === 1) {
  //         expense += Number(bills[index].amount)
  //         setExpense(expense);
  //       }else{
  //         income += Number(bills[index].amount)
  //       }
  //     })
  //   })
  // },[bill.bills])
  useEffect(() => {
    const _expense = bill.bills.filter(i => i.pay_type == 1).reduce((pre, item) => {
      pre += Number(item.amount)
      return pre
    }, 0)
    setExpense(_expense)

    const _income = bill.bills.filter(i => i.pay_type == 2).reduce((pre, item) => {
      pre += Number(item.amount)
      return pre
    }, 0)
    setIncome(_income)
  })

  const goToDetail =(item) => {
    navigate({pathname: '/detail', query: {id: item.id}})
    // navigate(`/detail?id=${item.id}`)
  }

  return (
    <div className={s.item}>
      <div className={s.headerDate}>
        <div className={s.date}>{bill.date}</div>
        <div className={s.money}>
          <span>
            <img src="//s.yezgea02.com/1615953405599/zhi%402x.png" alt='支' />
            <span>¥{expense.toFixed(2)}</span>
          </span>
          <span>
            <img src="//s.yezgea02.com/1615953405599/shou%402x.png" alt="收" />
            <span>¥{income.toFixed(2)}</span>
          </span>
        </div>
      </div>
      {
        bill && bill.bills.sort((a, b) => b.date - a.date).map(item => <Cell
          className={s.bill}
          key={item.id}
          onClick={() => goToDetail(item)}
          title={
            <>
              <span>{item.type_name}</span>
            </>
          }
          description={<span style={{ color: item.pay_type == 2 ? 'red' : '#39be77' }}>{`${item.pay_type == 1 ? '-' : '+'}${item.amount}`}</span>}
          help={<div>{dayjs(Number(item.date)).format('HH:mm')} {item.remark ? `| ${item.remark}` : ''}</div>}
        >
        </Cell>)
      }
    </div>
  )
}

export default BillItem;
